package com.heima.user.service.impl;

import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.UserService;
import com.heima.user.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null || user.getId() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Integer userId = user.getId();
        Long articleId = dto.getArticleId();
        Integer authorId = dto.getAuthorId();
        Short operation = dto.getOperation();


        if (operation == 0){
            //添加关注
            //给用户添加关注的用户
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + userId,authorId.toString(),System.currentTimeMillis());
            //给被关注的用户添加粉丝
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION + authorId,userId.toString(),System.currentTimeMillis());
        }else if(operation == 1){
            //取消关注
            //删除用户关注的这个作者
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + userId,authorId.toString());
            //删除作者粉丝中的用户
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + authorId,userId.toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
